package com.smartcruise.main;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.smartcruise.R;
import com.smartcruise.base.BaseActivity;
import com.smartcruise.main.contactsFragment.ContactsFragment;
import com.smartcruise.main.mainFragment.MainFragment;
import com.smartcruise.main.selfFragment.SelfFragment;
import com.smartcruise.service.MainService;
import com.smartcruise.util.FragmentUtils;
import com.smartcruise.util.IntentUtils;
import com.smartcruise.util.SPUtils;
import com.smartcruise.util.TempleUser;
import com.smartcruise.util.runtimePermission.AndPermission;
import com.smartcruise.util.runtimePermission.CheckPermission;
import com.smartcruise.util.runtimePermission.PermissionNo;
import com.smartcruise.util.runtimePermission.PermissionYes;
import com.smartcruise.util.runtimePermission.Rationale;
import com.smartcruise.util.runtimePermission.RationaleListener;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by FengChaoQun
 * on 2018/1/18 0018
 * 主界面 管理三个fragment
 */

public class MainActivity extends BaseActivity {

    @BindView(R.id.mainContainer)
    FrameLayout mainContainer;
    @BindView(R.id.mainLay)
    FrameLayout mainLay;
    @BindView(R.id.contactsLay)
    FrameLayout contactsLay;
    @BindView(R.id.selfLay)
    FrameLayout selfLay;

    private Fragment mainFragment;
    private Fragment contactsFragment;
    private Fragment selfFragment;

    private MainService mainService;
    private boolean mBound;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setEnableRightSlide(false);
        doSomethingWhenEnter();
        initFragment(savedInstanceState);
        initView();
        requestBasicPermission();
    }

    /**
     * description:当用户进入主页面的时候 进行一些数据处理
     */

    private void doSomethingWhenEnter() {
        SPUtils.setIsQuit(false);//进入到该界面 清除用户的退出记录
        /*
         * 2018/2/6 0006 20:09
         * 初始化当前用户的信息 方便后面提取
         * 这一步放在清除退出记录之后 否则 在没有用户信息的时候 会退出APP 让用户重新登录 但是随后的代码又将退出记录清空
         * 导致没有退出的记录
         * */
        TempleUser.getInstance().init();
        JPushInterface.setAlias(getActivity(), 1, TempleUser.getInstance().getAccount());
        JPushInterface.resumePush(getActivity());

        //设置bugly的用户id
        CrashReport.setUserId(TempleUser.getInstance().getUserInfo().getPhoneNumber());
    }

    /**
     * description:初始化fragment
     * 当该界面重绘的时候 直接取出保存的fragment
     */

    private void initFragment(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mainFragment = FragmentUtils.find(mFragmentManager, MainFragment.class);
            contactsFragment = FragmentUtils.find(mFragmentManager, ContactsFragment.class);
            selfFragment = FragmentUtils.find(mFragmentManager, SelfFragment.class);
        }
    }

    private void initView() {
        onMainLayClicked();
    }

    private void showMainFragment() {
        mainFragment = FragmentUtils.find(mFragmentManager, MainFragment.class);
        if (mainFragment == null) {
            mainFragment = new MainFragment();
            FragmentUtils.add(mFragmentManager, R.id.mainContainer, mainFragment);
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (contactsFragment != null) {
            transaction.hide(contactsFragment);
        }
        if (selfFragment != null) {
            transaction.hide(selfFragment);
        }
        transaction.show(mainFragment).commitNowAllowingStateLoss();
    }

    private void showContactsFragment() {
        contactsFragment = FragmentUtils.find(mFragmentManager, ContactsFragment.class);
        if (contactsFragment == null) {
            contactsFragment = new ContactsFragment();
            FragmentUtils.add(mFragmentManager, R.id.mainContainer, contactsFragment);
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (mainFragment != null) {
            transaction.hide(mainFragment);
        }
        if (selfFragment != null) {
            transaction.hide(selfFragment);
        }
        transaction.show(contactsFragment).commitNowAllowingStateLoss();
    }

    private void showSelfFragment() {
        selfFragment = FragmentUtils.find(mFragmentManager, SelfFragment.class);
        if (selfFragment == null) {
            selfFragment = new SelfFragment();
            FragmentUtils.add(mFragmentManager, R.id.mainContainer, selfFragment);
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (mainFragment != null) {
            transaction.hide(mainFragment);
        }
        if (contactsFragment != null) {
            transaction.hide(contactsFragment);
        }
        transaction.show(selfFragment).commitNowAllowingStateLoss();
    }

    @OnClick(R.id.mainLay)
    public void onMainLayClicked() {
        mainLay.setSelected(true);
        contactsLay.setSelected(false);
        selfLay.setSelected(false);
        showMainFragment();
    }

    @OnClick(R.id.contactsLay)
    public void onContactsLayClicked() {
        mainLay.setSelected(false);
        contactsLay.setSelected(true);
        selfLay.setSelected(false);
        showContactsFragment();
    }

    @OnClick(R.id.selfLay)
    public void onSelfLayClicked() {
        mainLay.setSelected(false);
        contactsLay.setSelected(false);
        selfLay.setSelected(true);
        showSelfFragment();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void startService() {
        Intent intent = new Intent(getActivity(), MainService.class);
        startService(intent);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    public void endService() {
        stopService(new Intent(getActivity(), MainService.class));
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        endService();
    }

    /**
     * description:请求基本的权限 如果这些申请被拒绝 那么无法使用APP
     */

    private void requestBasicPermission() {
        AndPermission.with(getActivity())
                .requestCode(IntentUtils.GET_BASIC_PERMISSION)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.READ_PHONE_STATE)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框，避免用户勾选不再提示。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(getActivity(), rationale)
                                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                }).show();
                    }
                })
                .send();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //申请权限成功 检查权限
    @PermissionYes(IntentUtils.GET_BASIC_PERMISSION)
    private void getBasicGrant(List<String> grantedPermissions) {
        if (!CheckPermission.isGranted(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                || !CheckPermission.isGranted(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
            showPermissionRejectedDialog();
        } else {
            //申请权限成功后 开启服务
            startService();
        }
    }

    //申请权限失败
    @PermissionNo(IntentUtils.GET_BASIC_PERMISSION)
    private void getBasicDenine(List<String> deniedPermissions) {
        showToast("获取基本权限失败!");
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            showPermissionRejectedDialog();
        } else {
            requestBasicPermission();
        }
    }

    private void showPermissionRejectedDialog() {
        AndPermission.defaultSettingDialog(this, IntentUtils.GET_BASIC_PERMISSION)
                .setTitle("权限申请失败")
                .setMessage("我们需要了解你手机的状态并存储一些必要的信息,请在设置界面的权限管理中开启,否则无法使用本软件.")
                .setPositiveButton("好,去设置")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentUtils.GET_BASIC_PERMISSION) {
            requestBasicPermission();
        }
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MainService.MainBinder mainBinder = (MainService.MainBinder) service;
            mainService = mainBinder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

}
